import { Toast ,Popover, NavBar ,Icon ,Result,Button,List ,InputItem } from 'antd-mobile'
import {Spin,Table,Divider,Tag} from 'antd'
import { createForm } from 'rc-form';
import React ,{useState,useEffect} from 'react';
import {connect} from 'react-redux'
import {LoginAction} from '../../store/actions'

import defaultimg from '../../statics/img/logo.png'
import logoout from '../../statics/img/logoout.svg'
import innerman from '../../statics/img/innerman.svg'
import change_avatar from '../../statics/img/change_avatar.svg'
import application from '../../statics/img/application.svg'

import {getapplylist,getapplyres,updateavatar,usrlogout,manageapply} from '../../network/profile'

import './profile.css'
import { idname } from './util.js'

import Qs from 'querystring'


const Item = Popover.Item
 
const Profile = (props) =>{

  const [imgUrl,setimgUrl]  =useState(defaultimg)
  const [visible,setvisible]  =useState(false)
  const [selected,setselected] =useState('')
  const [application_list,setapplication_list] =useState([])
  const [isapply_loading,setisapply_loading]  =useState(false)
  const [have_applied,sethave_applied]  =useState(false)
  const [selected_user,setselected_user] =useState([])
  const [allowed_user_key,setallowed_user_key] =useState([])
  const [confused_user_key,setconfused_user_key] =useState([])   
  const [show_applylist,setshow_applylist] =useState(false)
  const [show_applyinfo,setshow_applyinfo] =useState(false) 


  const {username,identity,avatar} = props
  const { getFieldProps, getFieldError } = props.form;

  
  useEffect(()=>{
      
      if(username == ""){
        Toast.info('登录过期，请重新登录！')
        props.history.push({pathname:'/main/login'})
      }
      else {
        Toast.info(
          '欢迎！ '+ idname(identity) +" "+username ,2
        )
        //头像设置
        if(avatar !== null)
        {
          setimgUrl(avatar)
        }  
      }
  },[])

  const onSubmit = () => {
    setisapply_loading(true)
    props.form.validateFields({ force: true }, (error) => {
      if (!error) {
        const userdata =Qs.stringify({
         ...props.form.getFieldsValue()
        })
        const apply_for_inner = async()=>{
          const apply_result = await getapplyres(userdata)
          setisapply_loading(false)
          switch (apply_result.code){
            case 1201 : Toast.info('一周之内不能重复申请！') ;sethave_applied(true) ;break
            case 600 : Toast.info('登录失效！请重新登录') ; props.history.push('/main/login') ;break
            case 200 : Toast.success('申请成功！');sethave_applied(true) ; break
            default : console.log(apply_result);
          }
        }
        apply_for_inner()

      }
        else {
 
      }
    });
  }
 
  const onSelect = (opt) => {
  
    setvisible(false)
    setselected(opt.props.value)
    if(opt.props.value == 'logout')
    {
      logout()
    }
  };

  const handleVisibleChange = (visible) => {
    setvisible(visible)
  };

  const uploadimg = (e) => {
    const {setusravatar} =  props
      let file = e.target.files[0];
      let avatar = new FormData(); //创建form对象
      // let imgUrl = URL.createObjectURL(file);
      // this.setState({
      //   imgUrl
      // })
      avatar.append('avatar',file);//通过append向form对象添加数据
      const update_avatar = async() => {
        const update_res = await updateavatar(avatar)
        setusravatar({avatar:update_res.data.avatar + '?' + Math.random()})
        setimgUrl(update_res.data.avatar + '?' + Math.random())
      }

      update_avatar()
  }
  
  const logout = () =>{
    const { setusrinfo} = props
    const usr_logout = async () =>{
      const logout_res = await usrlogout()
      if(logout_res.code == 200){
        Toast.info('注销成功')
        setusrinfo({username:'',identity:'',avatar:''})
        props.history.push('/main/login');
      }
    }
    usr_logout()
  }


  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      responsive:['xs']
    },
    {
      title: '真实姓名',
      dataIndex: 'realname',
      responsive:['xs']
    },
    {
      title: '电话',
      dataIndex: 'phonenumber',
      responsive:['xs']
    }
  ];

 
  const addmit = (selected)=>{
    const oklist = []
    for (var usr of selected)
    {
      oklist.push(usr.username)
    }

    send_judge(oklist,true)
  }

  const refused = (selected)=>{
    const noklist = []
    for (var usr of selected)
    {
      noklist.push(usr.username)
    }
    send_judge(noklist,false)
  }

  const send_judge = (selectlist,allow)=>{
    const mange_apply = async()=>{
      const manage_res = await manageapply(selectlist,allow)
      if (manage_res.code === 200){
        if (selectlist.length ===application_list.length){
         setapplication_list([])
        }
        else { 
        }
      }
    }
    mange_apply()
  }

  
  const use_friend = () =>{
    props.history.push('/main/profile/friend')
  }

  const use_applyinner = () => {
    const {identity} = props
    
    if (identity === 'inner' || identity ==='admin' )
    {
      Toast.info('只有外部成员才能申请成为内部成员！',2)
    }
    else{
      setshow_applyinfo(true)
    }
    
  }

  const use_application = () => {
    //身份判断
    if (identity !== 'admin'  )
    {
      Toast.info('只有管理员才能进行审批！',2)
    }
    else{
        //管理员则请求申请列表
          const get_applylist = async() => {
            const apply_res = await getapplylist()
            if(apply_res.code === 200 )
            {
              const apply_list = []
              for (var apply_item of apply_res.data)
              {
                apply_item.description = "申请日期：" + apply_item.date +" " + "申请信息：" +apply_item.info
                apply_item.key = apply_item.id
                delete apply_item.id
                delete apply_item.date
                delete apply_item.info
                apply_list.push(apply_item)
                
              }
              setapplication_list(apply_list)      
            }
          }     
      get_applylist() 
      setshow_applylist(true)
    }
  }


  return (
    <div className='profile'>
      <NavBar
      mode="dark"
      rightContent={
        <Popover 
          overlayClassName="fortest"
          overlayStyle={{ color: 'currentColor' }}
          visible={visible}
          overlay={[
            (<Item key="4" value="logout"  data-seed="logId11">注销</Item>)
          ]}
          align={{
            overflow: { adjustY: 0, adjustX: 0 },
            offset: [-10, 0],
          }}
          onVisibleChange={handleVisibleChange}
          onSelect={onSelect}
        >
            <div style={{
            height: '100%',
            padding: '0 15px',
            marginRight: '-15px',
            display: 'flex',
            alignItems: 'center',
          }}
          >
            <img  src={logoout} height= {20} />
          </div>
        </Popover>
      }
      >
        用户中心
      </NavBar>
        
      <div className='p_title' >
        <div className='avatar'>  
          <div>
            <label htmlFor="file"  >
            <img src={imgUrl} alt='avatar' height={'100'} htmlFor="file" ></img>   
            </label>
          </div>
          
        </div>
        <div className='p_title_ni'>
         
          <div className='p_title_identity'>
            <Tag color="#55acee">
              {idname(identity)}
            </Tag>
          </div>
          <div className='p_title_name'>{username}</div>
        </div>
       
        <input type="file" accept="image/png,image/jpeg" onChange={uploadimg}  id="file"  style={{display: 'none'}}/>
      </div>
      
    
      <div className='p_content'> 
   
        <div className="totalservice">

          {/* <div className="service change_avatar">
          <label htmlFor="file"  >
            <img src={change_avatar}/>
            <div>头像变更</div>
          </label>
          </div> */}

          <div className="service friend" onClick={use_friend}>
            <img src={change_avatar}/>
            <div>好友</div>
          </div>
  
          <div className="service apply_inner" onClick={use_applyinner}>
            <img src={innerman}/>
            <div>申请内部成员</div>
          </div>

          <div className="service application" onClick={use_application}>
            <img src={application}/>
            <div>审批申请</div>
          </div>

          

          

        </div>
        <div style={{margin:'0 25px 0 25px'}}>
        <Divider orientation="center">服务</Divider>
        </div>
        <div className="service_zone">
        {
          show_applylist === true ? 
          application_list.length == 0 ? 
          
          <Result
          img={<Icon type="check-circle" className="spe" style={{ fill: '#1F90E6'}} size='lg' />}
          title="审批完毕"
          /> 
          :
          
          <div className="apply_list">
            <div>申请列表</div>
            <Table
                size= 'small'
                rowSelection={
                  {
                    columnWidth:'10px',
                    fixed : false,
                    onChange: (selectedRowKeys, selected_user) => {
                      setselected_user(selected_user)        
                    },
                    getCheckboxProps: (record) => ({
                      disabled: record.name === 'Disabled User',
                      // Column configuration not to be checked
                      name: record.name,
                    }),
                }}
                scroll={{
                  x:'max-content'
                  
                }}
                
                expandable={{
                  columnWidth:'0px',
                  expandRowByClick:true,
                  expandedRowRender: record => <p style={{ marginLeft: '20px' }}>{record.description}</p>,
                
                }}
                columns={columns}
                dataSource={application_list}
            />

            <Button type="primary" inline style={{marginRight:'15px'}} onClick={()=>addmit(selected_user)}>同意</Button>
            <Button type="warning" inline style={{marginLeft:'15px'}} onClick={()=>refused(selected_user)}>拒绝</Button>
          </div>
          
          : have_applied == false ? show_applyinfo === false ? <div></div> :
          <Spin spinning = {isapply_loading}>
              <List
                renderHeader={() => '申请成为内部成员'}
                renderFooter={() => getFieldError('realname') && getFieldError('realname').join(',')}
              >
                <InputItem
                  {...getFieldProps('realname', {
                    
                    rules: [
                      { required: false, message: '请输入真实姓名' },
                    
                    ],
                  })}
                  clear
                  error={!!getFieldError('realname')}
                  onErrorClick={() => {
                    alert(getFieldError('realname').join('、'));
                  }}
                  
                >真实姓名</InputItem>
                <InputItem {...getFieldProps('phonenumber',{  
                    rules: [
                      { required: false, message: '请输入手机号码' },  
                    ],
                  })}  
                  type="phone"  >
                  手机号码
                </InputItem>
                <InputItem {...getFieldProps('info',{
                    rules: [
                      { required: false, message: '请输入相关信息' },
                    ],
                  })}
                    type="text">
                  相关信息
                </InputItem>

                <Item>
                  <Button type="primary" size="small" inline onClick={onSubmit}>申请</Button>
                </Item>
            </List>
          </Spin> :  
            <Result
              img={<Icon type="check-circle" className="spe" style={{ fill: '#1F90E6'}} size='lg' />}
              title="申请成功"
              
            />
        }
        </div>
      </div>

        

        
      </div>
      
    )
  
  
  
}

const ProfileWrapper = createForm()(Profile)

//mapState2Props返回的对象中的key，value作为传递给ui组件的props的key,value——用于传递状态
const mapState2Props = (state) => 
  ({
      username : state.getIn(['login','usr']),
      identity : state.getIn(['login','identity']),
      avatar : state.getIn(['login','avatar'])
  })


//mapDispatch2Props返回的对象中的key，value作为传递给ui组件的props的key,value————用于传递操作状态的方法
//一般写法-》方法
// const mapDispatch2Props = (dispatch) => {
//   return{
//     setusrinfo(data){
//       dispatch(LoginActionCreators.setuserinfo(data))
//     }
//   }
// }

//简写mapDispatch2Props-》对象
const mapDispatch2Props = {
  setusrinfo : LoginAction.setuserinfo,
  setusravatar : LoginAction.setusravatar
}

//connect()(UI组件) ——>返回容器组件 
export default connect(mapState2Props,mapDispatch2Props)(ProfileWrapper)  